package com.im.server.special.business.service;

import java.util.Hashtable;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author XiaHui
 * @date 2017年8月19日 上午8:09:19
 */
@Component
public class LdapHandler {

	@Value("${ldap.server.url}")
	String ldapServerUrl;
	@Value("${ldap.server.domain}")
	String ldapServerDomain;

	public String handleAccount(String account) {
		if (null != account) {
			account = account.replace(ldapServerDomain, "");
		}
		return account;
	}

	public boolean auth(String username, String password) {
		if (!username.endsWith(ldapServerDomain)) {
			username = username + ldapServerDomain;
		}
		return auth(ldapServerUrl, username, password);
	}

	public boolean auth(String url, String username, String password) {
		// 设置相关常量
		String initialContextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
		// String ad4ProviderURL ="ldap://182.254.139.73:389";
		String securityAuthentication = "simple";

		/*
		 * 组织参数集合
		 */
		Hashtable<String, String> env = new Hashtable<String, String>();
		// set the initializing information of the context
		env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
		// set the URL of ldap server
		env.put(javax.naming.Context.PROVIDER_URL, url);
		// set the authentication mode
		env.put(javax.naming.Context.SECURITY_AUTHENTICATION, securityAuthentication);
		// set user of AD
		env.put(javax.naming.Context.SECURITY_PRINCIPAL, username);
		// set password of user
		env.put(javax.naming.Context.SECURITY_CREDENTIALS, password);

		/*
		 * 进行LDAP连接
		 */
		javax.naming.ldap.LdapContext ctx = null;

		try {
			// initialize the ldap context
			ctx = new javax.naming.ldap.InitialLdapContext(env, null);
		} catch (javax.naming.NamingException ex) {
			return false;
		} finally {
			if (ctx != null) {
				try {
					ctx.close();
				} catch (javax.naming.NamingException ex) {
					ex.printStackTrace();
				}
				return true; // 获取的LdapContext对象不为空，则为登录成功
			}
		}
		return false; // 否则登录失败
	}
}
